<template>
    <div class="album-list">
        <nav-header></nav-header>
        <div class="zh-table">  

            <!-- 搜索栏 -->
            <div class="zh-table-open clear">
                <div class="zh-open-left fl">
                    <div class="open-width" style="width: 120px">
                        <el-select v-model="leave_type" filterable placeholder="请选择">
                            <el-option
                                v-for="(item, index) in statusOptons"
                                :key="index"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="open-width" style="width: 220px">
                    <el-input v-model="keyword" placeholder="名称，创建人" @keyup.enter.native="searchFunc"></el-input>
                    </div>
                    <el-button type="primary"  @click="searchFunc">搜索</el-button>
                    <el-button type="primary"  @click="reset">重置</el-button>
                </div>
                <div class="zh-open-right fr">
                    <el-button type="primary" @click="turnBuilt">新建相册</el-button>
                    <el-button type="danger" @click="deleteChosen">批量删除</el-button>
                </div>
            </div>

            <!-- 表格 -->
            <div class="ablum-table zh-table-contents" v-loading="loading.status" :element-loading-text="loading.txt">
                <el-table
                    max-height="541"
                    ref="multipleTable"
                    :data="albumList"
                    border
                    @select-all="selectAll"
                    @select="handleSelectionChange">
                    <el-table-column
                        type="selection" 
                        width="56"
                        :selectable="selectable"
                        fixed>
                    </el-table-column>
                    <el-table-column
                        prop="name"
                        label="相册名称"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="pic_detail_count"
                        label="图片数量"
                        width="120">
                    </el-table-column>
                    <el-table-column
                        prop="username"
                        label="创建人">
                    </el-table-column>
                    <el-table-column
                        prop="create_time"
                        label="创建时间"
                        width="200">
                    </el-table-column>
                    <el-table-column
                        label="相册状态"
                        width="120">
                        <template slot-scope="scope">{{ leaveStatus[scope.row.status] }}</template>
                    </el-table-column>
                    <el-table-column
                        prop="control"
                        label="操作">
                        <template slot-scope="scope">
                            <el-button type="text" @click="albumDetails(scope.row.id)">详情</el-button>
                            <template v-if="parseInt(scope.row.status) != 2">
                                <el-button v-if="parseInt(scope.row.status) == 1" @click="pushIndexBox(scope.row)" type="text">推首页</el-button>
                                <el-button @click="deleteCurrent(scope.row)" class="delete-button" type="text">删除</el-button>
                            </template>
                            <template v-if="parseInt(scope.row.status) ==2">
                                <el-button @click="approve(scope.row)" type="text">通过</el-button>
                                <el-button @click="showReject(scope.row)" class="reject-button" type="text">拒绝</el-button>
                            </template>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页组件 -->
                <div class="table-pagination" v-show="total_number > 10">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="listParam.page_index"
                        :page-sizes="[10, 20, 30, 40, 50, 100]"
                        :page-size="listParam.size"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total_number">
                    </el-pagination>
                    <div class="pagination-button">
                        <el-button 
                            @click="getList"
                            type="primary" icon="el-icon-refresh" 
                            circle title="刷新数据" size="mini" >
                        </el-button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 拒绝弹窗 -->
        <el-dialog
            title="拒绝"
            :visible.sync="rejectWin"
            :close-on-click-modal="false" 
            :close-on-press-escape="false"
            width="40%"
            >
            <div class="textarea-box">
                <el-form :model="rejectForm"  ref="rejectForm" label-width="80px" class="demo-ruleForm">
                    <el-form-item label="拒绝理由" prop="txt" :rules="[{max:100,message:''}]">
                    <el-input type="textarea" placeholder="输入拒绝理由（非必填）" v-model="rejectForm.txt" :maxlength="100" required></el-input>
                    </el-form-item>
                </el-form>
                <p class="str-num"><span v-text="rejectForm.txt.length"></span>/<span class="str-max">100</span></p>
            </div>
            <p class="tip">提示：拒绝将删除相册数据</p>
            <span slot="footer" class="dialog-footer">
                <el-button @click="rejectWinHide">取 消</el-button>
                <el-button type="primary" @click="reject">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 推首页 -->
        <el-dialog
            title="首页展示"
            :visible.sync="homeVisible"
            width="800px"
            custom-class="home-page"
            :close-on-click-modal="false">
            <div class="home-page-c">
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                    <!-- <div class="home-page-t">
                        请选择首页位置：<span>专辑 《{{pushObj.name}}》将放置在 “位置{{ruleForm.selectIndex+1}}”</span>
                    </div> -->
                    <el-form-item label-width="0" prop="selectIndex">
                        <el-radio-group v-model="ruleForm.selectIndex">
                            <el-radio v-for="(item,inx) in positionData" @change="renderPushHtml" :key="inx" :label="inx" class="page-checked">
                                <div class="home-page-ls">
                                    <div>
                                        <img :src="BASE_URL+item.pic_path" > 
                                        <i class="el-icon-error" v-if="parseInt(item.id) > 0 && parseInt(pushObj.pic_id) != parseInt(item.pic_id) " @click.prevent="deletePushIndex(inx)"></i>

                                    </div>
                                    <p>位置{{inx+1}}</p>
                                </div>
                            </el-radio>
                        </el-radio-group>

                    </el-form-item>
                    <el-form-item label-width="0" class="controls-bar">
                        <el-button @click="pushToTop">首页置顶</el-button>
                        <el-button @click="resetForm('ruleForm')" type="primary" plain>重置</el-button>
                       <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
                      
                     </el-form-item>
                </el-form>
            </div>
            <!-- <div slot="footer" class="dialog-footer"></div> -->
        </el-dialog>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                rejectWin: false /*拒绝弹窗 */,
                rejectObj: null /*拒绝对象 */,
                rejectForm: {
                    txt: "" /*拒绝理由填写 */
                },
                // 加载数据时显示的信息和加载动画
                loading:{
                    status:false,
                    txt:'获取数据...',
                },
                keyword:'',      // 搜索框输入的关键字
                total_number:0,     // 存放一共有多少条文章的数量
                // 表单显示的数据
                albumList: [],
                multipleSelection: [],     // 存放已选项的数组
                listParam:{
                    status:-1,     // 状态，-1：全部；1：已通过；2：审核中；3：已拒绝'
                    page_index:1,     // 无
                    page_size:10,     // 无
                    data_type:1,     // 0：没有分页 ； 1：有分页
                    keyword:'',     // 关键字搜索（相册名，创建者名）
                },
                leave_type:0,     // 等于statusOptions被选中的索引值
                leaveStatus:['删除','已通过','审核中','拒绝'],     // 相片的审批状态（'0：删除；1：已通过；2：审核中；3：拒绝'）
                statusOptons: [{
                    value:0 ,
                    label: '全部状态'
                },{
                    value: '1',
                    label: '已通过'
                }, {
                    value: '2',
                    label: '未审批'
                }],
                // 推首页弹窗
                homeVisible: false,     // 控制推首页弹窗的显隐
                ruleForm: {
                    selectIndex: null,      // 当前选中的单选框
                },
                pushObj:{},      // 存放推送的对象
                tempPositionData:[],      // 存放后端返回有固定位置的相册的数组
                positionData:[],     // 控制位置的数组
                home_flag:1,
                rules: {
                    selectIndex: [
                          { required: true, type: 'number', message: '请选择一个位置', trigger: 'change'}
                    ],
                },
            }
        },
        created(){
            // 获取列表信息
            this.getList()
        },
        methods: {
            // 跳转到新建相册
            turnBuilt(){
                this.$router.push('/life/alumni/album-built')
            },
            // 判断选择框是否可选 
            selectable(row, index){
                if(row.status == 2){
                    return false
                }else{
                    return true
                }
            },
            // 点击全选时执行的方法
            selectAll(selection){
                this.multipleSelection = selection.filter(item=>item.status == 1 || item.status == 3);

            },
            // 点击多选框时执行的方法
            handleSelectionChange(val) {
                // console.log(val)
                var lastItem = val[val.length-1];
                // console.log(lastItem)

                if(lastItem && lastItem.status==2){
                    this.$refs.multipleTable.toggleRowSelection(lastItem);
                    this.$message({
                      message: '未审核的相册不可选',
                      type: 'warning'
                    })
                    return
                }

                this.multipleSelection = val;
            },
            // 当改变每页展示数量时执行的方法
            handleSizeChange(val) {
                this.listParam.page_index = 1;
                this.listParam.page_size = val;
                this.getList()
                // console.log('handleSizeChange:',this.listParam)
            },
            // 当改变页码是执行的方法
            handleCurrentChange(val) {
                this.listParam.page_index = val;
                this.getList();
                // console.log('handleCurrentChange:',this.listParam)
            },
            album(id){
                this.$router.push('alumni-artical-details/'+id)
            },
            // 按关键字的搜索
            searchFunc(){
                // console.log('搜索关键字：',this.keyword)
                var status = this.leave_type;
                status = status==0? -1 : status;
                this.listParam.page_index = 1;     // 无
                this.listParam.status = status;     // 状态，-1：全部；1：正常；2：审核中；
                this.listParam.keyword = this.keyword;     // 关键字搜索（文章标题或创建者名）
                this.getList();
            },
            // 重置
            reset(){
                this.listParam.page_index = 1;     // 无
                this.listParam.status = -1;     // 状态，-1：全部；1：正常；2：审核中；
                this.listParam.keyword = this.keyword = '';     // 关键字搜索（文章标题或创建者名）
                this.getList(); 
            },
            // 获取数据列表
            getList(){
                // 显示加载动画
                this.loading.status = true;
                let success = (res=>{
                    // 隐藏加载动画
                    this.loading.status = false;

                    var data = res.data;
                    // console.log(data)
                    this.total_number = data.data_sum;

                    this.albumList = data.data

                })
                let fail = ( data => {
                    // 隐藏加载动画
                    this.loading.status = false;
                })
                //执行请求，并将回调方法变成config成员以便鉴权过期可以执行
                this.$ajax.get('api/alumni/alumniPic',{params: this.listParam,func:{success:success,fail:fail}})
            },
            // 批量删除
            deleteChosen(){
                // 获取到选中的文章id
                var deleteIds = this.multipleSelection.map(item=>item.id);
                // 如果没有选择删的项则报错提示
                if(deleteIds.length==0){
                    return this.$message.error('请选择要删除的项')
                }
                let yes = ( data => {
                    // console.log("删除当前ids:",deleteIds)
                    let success = ( data => {
                        // console.log('successs')
                        this.$message.success(data.msg);
                        
                        // 检测当前列表数据是否只有一条
                        if (this.albumList.length == 1) {
                            // 判断当前页面是否为第一页
                            if (this.listParam.page_index > 1) {
                                this.listParam.page_index-- ;
                            } else {
                                this.listParam.page_index = 1;
                            }
                        }

                        this.getList();
                    });
                    this.$ajax.delete('api/alumni/alumniPic',{params:{id:deleteIds},func:{success:success}})
                })
                let cancel = ( data => {})
                this.e_confirm({yes:yes,cancel:cancel,txt:'确定将 已选项 删除吗？'});
            },
            // 删除相册的方法
            deleteAblum(id){
                let success = ( data => {
                    this.$message.success(data.msg);

                    // 检测当前列表数据是否只有一条
                    if (this.albumList.length == 1) {
                        // 判断当前页面是否为第一页
                        if (this.listParam.page_index > 1) {
                            this.listParam.page_index-- ;
                        } else {
                            this.listParam.page_index = 1;
                        }
                    }

                    this.getList();
                });
                this.$ajax.delete('api/alumni/alumniPic',{params:{id:id},func:{success:success}})
            },
            // 删除当前
            deleteCurrent(obj){
                // console.log("删除当前id:",obj.id,obj)
                let yes = ( data => {
                    this.deleteAblum(obj.id);
                })
                let cancel = ( data => {})
                this.e_confirm({yes:yes,cancel:cancel,txt:'确定将 '+obj.name+' 删除吗？'});
            },
            // 通过审批的方法
            approve(obj){
                // console.log("通过审批")
                let yes = ( data => {
                    // console.log('确定')
                    let params = {
                        id: obj.id,   // 相册id
                        status: 1,   // 状态（1：通过；3：拒绝）
                    };
                    var success = res => {
                        this.$message.success(res.msg);
                        this.rejectWinHide();
                        this.getList();
                    };
                    this.$ajax.put("api/alumni/alumniPicApprove", params, {func: { success: success }});
                })
                let cancel = ( data => {})
                this.e_confirm({yes:yes,cancel:cancel,txt:'确定通过 '+ obj.name +' 的这个相册申请吗？'});
            },  
            // 显示拒绝弹窗的方法
            showReject(obj) {
                /*拒绝 */
                // console.log("拒绝",obj)
                this.rejectWin = true;
                this.rejectObj = obj;
                
            },
            // 确认拒绝的方法
            reject(){
                // console.log('确认拒绝')
                let params = {
                    id: this.rejectObj.id,    // 相册id
                    status: 3,    // 状态（1：通过；3：拒绝）
                    comment: this.rejectForm.txt
                };
                // console.log(this.rejectForm.txt)

                var success = res => {
                    // 操作提示
                    this.$message.success(res.msg);
                    // 拒绝后删除相册
                    // this.deleteAblum(params.id);
                    // 隐藏弹窗
                    this.rejectWinHide();
                    // 重新获取最新列表信息
                    this.getList();
                };

                this.$ajax.put("api/alumni/alumniPicApprove", params, {func: { success: success }});
            },
            // 隐藏拒绝弹窗
            rejectWinHide() {
                /*隐藏拒绝弹窗 */
                this.rejectWin = false;
                this.rejectForm.txt = "";
                this.rejectObj = null;
            },
            // 打开推首页弹窗方法
            pushIndexBox(obj){
                // console.log(obj)
                this.homeVisible = true;
                this.ruleForm.selectIndex = null;    // 默认单选框为非选中状态
                this.pushObj = {pic_id:obj.id,name:obj.name,pic_path:obj.pic_cover,position:null}
                this.getPosition();
            },
            getPosition(){
                this.loading.status = true;
                let success = (data=>{
                    // console.log(data)
                    this.loading.status = false;
                    this.tempPositionData = data.data;    // 存放有固定位置的相册数组
                    this.ruleForm.selectIndex = null;
                    this.renderPushHtml();
                })
                let fail = ( data => {
                    this.loading.status = false;
                    this.$message.error(data.msg)
                })
                //执行请求，并将回调方法变成config成员以便鉴权过期可以执行
                this.$ajax.get('api/alumni/pushToHome',{func:{success:success,fail:fail}})
            },
            // 单选框值改变后执行的方法
            renderPushHtml(){
                // console.info('单选框',this.ruleForm.selectIndex)
                this.positionData = [];
                for (var i = 0; i <= 3; i++) {
                    var temp_  = { id:null, position: i+1 , name:'' , pic_path: '/static/default/video_cover.png'}
                    for ( var j=0; j<this.tempPositionData.length; j++ ) {
                        if( (i+1) === parseInt( this.tempPositionData[j].position )  ){
                            if( is_empty(this.ruleForm.selectIndex) || ( !is_empty(this.ruleForm.selectIndex) && parseInt(this.pushObj.pic_id) !== parseInt( this.tempPositionData[j].pic_id )  )){
                                temp_ = deep_clone(this.tempPositionData[j]);
                                temp_.pic_path = this.tempPositionData[j].pic_path
                            }
                        }
                       
                    }
                    if( this.ruleForm.selectIndex === i ){
                        this.positionData.push(  this.pushObj );
                    }else{
                        this.positionData.push( temp_ );
                    }
                    
                }

                //取消首页置顶
                if( this.home_flag === 0 && this.ruleForm.selectIndex !== 0 ){
                    this.home_flag = 1;
                }
                
                // console.log('renderPushHtml:',this.positionData)
                // console.log('pushObj:',this.pushObj)
            },
            // 删除对应位置的图片
            deletePushIndex(inx){
                this.positionData[inx].id = null;
                this.positionData[inx].position = null;
                this.positionData[inx].name = '';
                this.positionData[inx].pic_path = '/static/default/video_cover.png'
                var deletet_inx =  -1;
                this.tempPositionData.forEach( (item ,inxx) =>{
                    if(parseInt(item.position)-1 === inx ){
                        deletet_inx = inxx;
                    }
                })
                deletet_inx > -1 && this.tempPositionData.splice( deletet_inx )
            },
            // 首页置顶
             pushToTop(){
                var newTemp = [];
                    newTemp.push( deep_clone( this.pushObj ) );
                var temp_  = { pic_id:null , position: null , name:'' , pic_path: '/static/default/video_cover.png'}
                var have_continued = false;//是否已经跳过第一个空的推首页项
                //去掉在里面的当前的推首页项
                for (var i = this.positionData.length - 1; i >= 0; i--) {
                    if( parseInt( this.pushObj.pic_id ) === parseInt( this.positionData[i].pic_id ) ){
                        this.positionData[i] =  deep_clone( temp_ );
                        break;
                    }
                }

                for ( var i = 0; i <= 4; i++ ) {
                    //第一个空的推首页项,往后空的就不会跳过
                    if( is_empty( this.positionData[i].id  ) && !have_continued ){
                        have_continued  = true;
                        continue;
                    }
                    newTemp.push( deep_clone( this.positionData[i] )  );
                    if( newTemp.length === 4 ){
                        break;
                    }

                } 

                this.home_flag = 0 ;
                this.ruleForm.selectIndex = 0;
                this.positionData = deep_clone( newTemp );          

                // console.log('pushToTop:',this.positionData)
            },
            // 重置数据
            resetForm(formName) {
                this.$refs[formName].resetFields();    // 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
                this.ruleForm.selectIndex = null;
                this.getPosition();
            },
            // 保存推首页信息
            submitForm(formName) {
                // console.log('保存')
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.savePosition();
                    } else {
                        return false;
                    }
                });
            },
            // 保存位置请求
            savePosition(){
                let success = ( data=>{
                    this.$message.success(data.msg);
                    this.homeVisible = false;
                })
                //alert(this.pushObj.pic_id)
                var params = {
                    position : [],
                    id : [],
                    resid : this.pushObj.pic_id,
                };
                console.log(this.positionData)
                for ( var i = 0; i < this.positionData.length; i++ ) {
                    if( !is_empty( this.positionData[i].pic_id ) ){
                        params.id.push( this.positionData[i].pic_id );
                        params.position.push( i+1 );
                    }
                    else{
                        params.id.push( null );
                        params.position.push( null );
                    }
                }
                this.$ajax.post('api/alumni/pushToHome',params,{func:{success:success}})
                
            },
            // 跳转至相册详情页的方法
            albumDetails(id){
                // console.log("跳转至详情页")
                this.$router.push('/life/alumni/album-details/' + id)
            },
        },
    }
</script>
<style lang="scss">
    .album-list {
        .ablum-table {
            margin-top:20px;
            table{
                thead{
                    tr{
                        th{
                            border:0 none;
                            text-align:center;
                            &.gutter{
                                width:0;
                            }
                        }
                    }
                }
                tbody{
                    tr{
                        td{
                            text-align:center;
                            button{
                                &.delete-button,&.reject-button{
                                    color:#dd6161;
                                }
                                &.el-button{
                                    min-width:38px;
                                    text-align:center;
                                }
                            }
                        }
                    }
                }
            }
        }
        .el-dialog__body{
            // 拒绝理由的样式
            .textarea-box{
                position: relative;
                .el-textarea__inner {
                    min-height: 120px !important;
                    resize: none;
                }
                .str-num {
                    position: absolute;
                    padding: 0;
                    margin: 0;
                    left: 0;
                    bottom: 5px;
                    right: 15px;
                    text-align: right;
                    .str-max {
                        color: #ddd;
                    }
                }
            }
            .tip{
                margin-left:16px;
            }


            // 推首页样式
            .page-checked{
                width: 177px;
                height: 150px;
                overflow: hidden;
                margin:0 10px 0 0 !important ;
                padding: 0;
                &:nth-of-type(4n){
                    margin-right: 0 !important ;
                }
                .el-radio__input{
                    position: absolute;
                    bottom: 10px;
                    left: 0;
                }
                .el-radio__label{

                }
                .home-page-ls{
                    >div{
                        position: relative;
                        width: 100%;
                        height: 100px;
                        overflow: hidden;
                        margin-bottom: 10px;
                        >img{
                            width: 100%;
                            height: 100%;
                            object-fit: cover;
                        }
                        >i {
                            position: absolute;
                            right: 5px;
                            top: 5px;
                            // color: #348efc;
                        }
                    }
                    >p{
                        margin: 0;
                        padding-left: 20px;
                    }
                }
            }
            .controls-bar{
                padding-bottom:18px;
            }
        }
        .pointer{
            cursor:pointer;
        }
    }
</style>